package com.cymjoe.testflutternativedemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel

class MainActivity : AppCompatActivity() {
    val nativeMethodChannel = "native/method/channel"
    val nativeEventChannel = "native/event/channel"

    var mEvents: EventChannel.EventSink? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val flutterEngine = FlutterBuilder.getInstance(this)?.flutterEngine;
        val methodChannel =
            MethodChannel(
                flutterEngine?.dartExecutor?.binaryMessenger,
                nativeMethodChannel
            )
        methodChannel.setMethodCallHandler { call, result ->
            when (call.method) {
                "mapData" -> {
                    if (call.arguments == null) {
                        return@setMethodCallHandler
                    }

                    val a = call.arguments as Map<*, *>
                    a.forEach {
                        Log.d("fromFlutter---->", "${it.key}=======>${it.value}")
                    }


                }
            }
            result.success("成功获取flutter参数")

        }
        val eventChannel =
            EventChannel(flutterEngine?.dartExecutor?.binaryMessenger, nativeEventChannel)
        eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                mEvents = events
            }

            override fun onCancel(arguments: Any?) {

            }

        })
    }

    var n = 0;
    fun btnClick(view: View) {
        n++;
        mEvents?.success("传递给flutter：您好$n")
        startActivity(
            FlutterActivity
                .withCachedEngine("start1")
                .build(this)
        )
    }

    fun btnClick2(view: View) {
        n++;
        mEvents?.success("传递给flutter：您好$n")
        startActivity(
            FlutterActivity
                .withCachedEngine("start2")
                .build(this)
        )
    }

    fun btnClick3(view: View) {
        n++;
        mEvents?.success("传递给flutter：您好$n")
        startActivity(
            FlutterActivity
                .withCachedEngine("start3")
                .build(this)
        )
    }
}